package com.ruoyi.safe.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NameUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.quality.domain.TQualityFileItem;
import com.ruoyi.quality.service.ITQualityFileItemService;
import com.ruoyi.safe.domain.BizDutyRegion;
import com.ruoyi.safe.domain.BizExtensionRequests;
import com.ruoyi.safe.domain.BizProjectCheckRecord;
import com.ruoyi.safe.domain.BizSafeAttach;
import com.ruoyi.safe.domain.dto.BizExtensionRequestsDTO;
import com.ruoyi.safe.domain.vo.BizExtensionRequestsVO;
import com.ruoyi.safe.domain.vo.ListRequestVo;
import com.ruoyi.safe.mapper.*;
import com.ruoyi.safe.service.IBizExcludePlanTaskService;
import com.ruoyi.safe.service.IBizExtensionRequestsService;
import com.ruoyi.safe.service.IBizProjectCheckRecordService;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 延期申请Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-08
 */

@Service
@RequiredArgsConstructor
public class BizExtensionRequestsServiceImpl implements IBizExtensionRequestsService {

    private final BizExtensionRequestsMapper bizExtensionRequestsMapper;

    private final BizProjectCheckRecordMapper projectCheckRecordMapper;

    private final CommonProjectMapper commonProjectMapper;

    private final IBizProjectCheckRecordService bizProjectCheckRecordService;

    private final SysUserMapper sysUserMapper;

    private final BizDutyRegionMapper bizDutyRegionMapper;

    private final IBizExcludePlanTaskService bizExcludePlanTaskService;

    private final BizSafeAttachMapper bizSafeAttachMapper;

    @Autowired
    private ITQualityFileItemService tQualityFileItemService;
    /**
     * 查询延期申请
     *
     * @param id 延期申请主键
     * @return 延期申请
     */
    @Override
    public BizExtensionRequests selectBizExtensionRequestsById(Long id) {
        return bizExtensionRequestsMapper.selectBizExtensionRequestsById(id);
    }

    /**
     * 查询延期申请列表
     *
     * @param bizExtensionRequests 延期申请
     * @return 延期申请
     */
    @Override
    public List<BizExtensionRequests> selectBizExtensionRequestsList(BizExtensionRequests bizExtensionRequests) {
        return bizExtensionRequestsMapper.selectBizExtensionRequestsList(bizExtensionRequests);
    }

    /**
     * 新增延期申请
     *
     * @param bizExtensionRequests 延期申请
     * @return 结果
     */
    @Override
    public int insertBizExtensionRequests(BizExtensionRequests bizExtensionRequests) {
        // 查询项目检查记录

        TQualityFileItem tQualityFileItem = tQualityFileItemService.selectTQualityFileItemById(bizExtensionRequests.getRecordId());

        // 查询延期申请列表
        List<BizExtensionRequests> bizExtensionRequestsList = bizExtensionRequestsMapper.selectBizExtensionRequestsList(
                BizExtensionRequests.builder()
                        .recordId(bizExtensionRequests.getRecordId())
                        .build());

        // 进行校验
        applyValidate(tQualityFileItem, bizExtensionRequestsList);

        bizExtensionRequests.setStatus("0");
        // 设置创建时间、用户名和创建者
        bizExtensionRequests.setCreateTime(DateUtils.getNowDate());
        bizExtensionRequests.setDateTime(bizExtensionRequests.getCreateTime());

        LoginUser loginUser = SecurityUtils.getLoginUser();
        String currentUsername = loginUser.getNickname();
        bizExtensionRequests.setReplyUser(tQualityFileItem.getCheckPeopleName());
        bizExtensionRequests.setUserName(currentUsername);
        bizExtensionRequests.setCreateBy(currentUsername);

        // 插入延期申请并返回插入结果
        return bizExtensionRequestsMapper.insertBizExtensionRequests(bizExtensionRequests);

    }

    /**
     * 修改延期申请
     *
     * @param bizExtensionRequests 延期申请
     * @return 结果
     */
    @Override
    public int updateBizExtensionRequests(BizExtensionRequests bizExtensionRequests) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        String currentUsername = loginUser.getNickname();
        bizExtensionRequests.setUpdateBy(currentUsername);
        bizExtensionRequests.setUpdateTime(DateUtils.getNowDate());
        return bizExtensionRequestsMapper.updateBizExtensionRequests(bizExtensionRequests);
    }

    /**
     * 批量删除延期申请
     *
     * @param ids 需要删除的延期申请主键
     * @return 结果
     */
    @Override
    public int deleteBizExtensionRequestsByIds(Long[] ids) {
        return bizExtensionRequestsMapper.deleteBizExtensionRequestsByIds(ids);
    }

    /**
     * 删除延期申请信息
     *
     * @param id 延期申请主键
     * @return 结果
     */
    @Override
    public int deleteBizExtensionRequestsById(Long id) {
        return bizExtensionRequestsMapper.deleteBizExtensionRequestsById(id);
    }

    /**
     * 查询自己待批复的数量
     *
     * @param listRequestVo 通用请求参数
     * @return 结果
     */
    @Override
    public int selectBizExtensionRequestsCount(ListRequestVo listRequestVo) {
        return bizExtensionRequestsMapper.selectBizExtensionRequestsCount(listRequestVo.getUserName());
    }

    /**
     * 获取待批复的延期申请列表
     *
     * @param listRequestVo 列表请求参数
     * @return 待批复的延期申请列表
     */
    @Override
    public List<BizExtensionRequestsVO> getDelay(ListRequestVo listRequestVo) {
        // 查询自己待批复的延期申请记录
        List<BizExtensionRequests> delay = bizExtensionRequestsMapper.getDelay(listRequestVo);
        if (CollectionUtil.isEmpty(delay)) {
            return new ArrayList<>();
        }

        // 查询所有的检查记录
        Set<Long> recordIds = delay.stream().map(BizExtensionRequests::getRecordId).collect(Collectors.toSet());
        List<BizProjectCheckRecord> bizProjectCheckRecords = projectCheckRecordMapper.selectBizProjectCheckRecordByIds(recordIds);
        List<BizDutyRegion> bizDutyRegions = bizDutyRegionMapper.selectBizDutyRegionList(new BizDutyRegion());
        List<BizSafeAttach> bizSafeAttaches = bizSafeAttachMapper.selectBizSafeAttachByBizIds(recordIds);

        // 映射延期申请数据到延期申请视图对象列表
        List<BizExtensionRequestsVO> extensionRequestsVOList = delay.stream().map(s -> {
            BizExtensionRequestsVO bizExtensionRequestsVO = new BizExtensionRequestsVO();
            BizProjectCheckRecord bizProjectCheckRecord = bizProjectCheckRecords.stream()
                    .filter(a -> s.getRecordId().equals(a.getId()))
                    .findFirst().orElse(null);
            if(bizProjectCheckRecord != null){
                mapDataToVO(bizExtensionRequestsVO, s, bizProjectCheckRecord, bizDutyRegions);
            }

            List<BizSafeAttach> bizSafeAttacheList = bizSafeAttaches.stream().filter(b -> b.getBizId().toString().equals(bizExtensionRequestsVO.getRecordId())).collect(Collectors.toList());

            bizExtensionRequestsVO.setAttachList(bizSafeAttacheList);
            return bizExtensionRequestsVO;
        }).collect(Collectors.toList());

        // 如果指定了记录ID，则过滤掉指定记录ID和审批人不是自己对应的延期申请
        if (ObjectUtil.isNotNull(listRequestVo.getRecordId())) {
            BizExtensionRequests bizExtensionRequests = delay.stream()
                    .filter(s -> "0".equals(s.getStatus()) && !s.getReplyUser().equals(listRequestVo.getUserName()))
                    .findFirst()
                    .orElse(new BizExtensionRequests());

            extensionRequestsVOList.removeIf(s -> ObjectUtil.isNotNull(bizExtensionRequests.getId()) &&
                    s.getId().intValue() == bizExtensionRequests.getId().intValue());
        }

        // 处理用户名称到昵称的转换
        NameUtils.handleUserNameToNickName(extensionRequestsVOList, sysUserMapper.selectUserListAll(), "checkPeople", "revisePeople", "replyUser","userName","reviewUserName");
        return extensionRequestsVOList;
    }
    /**
     * 将数据映射到延期申请视图对象
     *
     * @param bizExtensionRequestsVO 延期申请视图对象
     * @param bizExtensionRequests  延期申请记录
     * @param bizProjectCheckRecord 项目检查记录
     * @param bizDutyRegions       责任区域列表
     */
    private void mapDataToVO(BizExtensionRequestsVO bizExtensionRequestsVO, BizExtensionRequests bizExtensionRequests,
                             BizProjectCheckRecord bizProjectCheckRecord, List<BizDutyRegion> bizDutyRegions) {
        // 将项目检查记录的属性拷贝到延期申请视图对象
        BeanUtil.copyProperties(bizProjectCheckRecord, bizExtensionRequestsVO);
        // 将延期申请记录的属性拷贝到延期申请视图对象
        BeanUtil.copyProperties(bizExtensionRequests, bizExtensionRequestsVO);

        // 设置项目名称
        bizExtensionRequestsVO.setProjectName(commonProjectMapper.selectCommonProjectById(bizProjectCheckRecord.getProjectId()).getName());
        bizExtensionRequestsVO.setProjectId(bizProjectCheckRecord.getProjectId().toString());
        // 设置责任区域
        BizDutyRegion bizDutyRegion = bizDutyRegions.stream()
                .filter(c -> c.getId().toString().equals(bizProjectCheckRecord.getDutyArea()))
                .findFirst()
                .orElse(new BizDutyRegion());
        //操作状态
        String operationStatus = bizProjectCheckRecord.getRevisePeople().equals(bizExtensionRequestsVO.getReplyUser()) ?
                "2" :bizProjectCheckRecord.getNotifier().equals(bizExtensionRequestsVO.getReplyUser()) ?
                "1" : "0";

        bizExtensionRequestsVO.setOperationStatus(operationStatus);

        // 人员类型
        StringBuffer peopleType = new StringBuffer();
        if(bizProjectCheckRecord.getNotifier().equals(bizExtensionRequestsVO.getReplyUser())){
            //通知人
            peopleType.append(",0");
        }
        if(bizProjectCheckRecord.getCheckPeople().equals(bizExtensionRequestsVO.getReplyUser())){
            //整改人
            peopleType.append(",1");
        }
        if(bizProjectCheckRecord.getRevisePeople().equals(bizExtensionRequestsVO.getReplyUser())){
            //复查人
            peopleType.append(",2");
        }
        if(bizProjectCheckRecord.getNotifier().equals(bizExtensionRequestsVO.getReplyUser())){
            //通知人
            peopleType.append(",3");
        }
        if(peopleType.length() > 0){
            bizExtensionRequestsVO.setPeopleType(peopleType.toString().substring(1));
        }

        Set<Long> parentsRegion = bizExcludePlanTaskService.getParentsRegion(bizDutyRegions, bizDutyRegion);
        bizExtensionRequestsVO.setDutyArea(bizProjectCheckRecordService.getRegionNames(bizDutyRegions, parentsRegion));
    }

    @Override
    public Boolean handleDelay(BizExtensionRequestsDTO bizExtensionRequestsDTO) {
        BizExtensionRequests bizExtensionRequests = bizExtensionRequestsMapper.selectBizExtensionRequestsById(bizExtensionRequestsDTO.getId());
        bizExtensionRequests.setUpdateBy(bizExtensionRequestsDTO.getUserName());
        bizExtensionRequests.setUpdateTime(DateUtils.getNowDate());
        bizExtensionRequests.setReplyOpinion(bizExtensionRequestsDTO.getReplyOpinion());
        bizExtensionRequests.setStatus(bizExtensionRequestsDTO.getStatus());
        bizExtensionRequests.setReplyTime(DateUtils.getNowDate());
        bizExtensionRequestsMapper.updateBizExtensionRequests(bizExtensionRequests);
        if ("2".equals(bizExtensionRequestsDTO.getStatus())) {
            BizProjectCheckRecord bizProjectCheckRecord = projectCheckRecordMapper.selectBizProjectCheckRecordById(bizExtensionRequests.getRecordId());
            if ("1".equals(bizProjectCheckRecord.getOverdueRectification())) {
                bizProjectCheckRecord.setOverdueRectification("0");
            }
            bizProjectCheckRecord.setReviseTheDates(bizExtensionRequests.getExtensionTime());
            projectCheckRecordMapper.updateBizProjectCheckRecord(bizProjectCheckRecord);
        }
        return true;
    }

    @Override
    public Boolean insertBizExtensionRequests(BizExtensionRequestsDTO extensionRequestsDTO) {

        //原整改时间不能大于申请延期至时间
        if (extensionRequestsDTO.getExtensionTime().getTime() < extensionRequestsDTO.getFormerTime().getTime()) {
            throw new RuntimeException("原整改时间不能大于申请延期至时间");
        }
        // 查询项目检查记录
        TQualityFileItem tQualityFileItem = tQualityFileItemService.selectTQualityFileItemById(extensionRequestsDTO.getRecordId());

        // 查询延期申请列表
        List<BizExtensionRequests> bizExtensionRequestsList = bizExtensionRequestsMapper.selectBizExtensionRequestsList(
                BizExtensionRequests.builder()
                        .recordId(extensionRequestsDTO.getRecordId())
                        .build());

        // 进行校验
        applyValidate(tQualityFileItem, bizExtensionRequestsList);

        // 将DTO转换为实体对象
        BizExtensionRequests bizExtensionRequests = new BizExtensionRequests();
        BeanUtil.copyProperties(extensionRequestsDTO, bizExtensionRequests);

        // 设置创建时间、用户名和创建者
        bizExtensionRequests.setCreateTime(DateUtils.getNowDate());
        bizExtensionRequests.setDateTime(DateUtils.getNowDate());
        bizExtensionRequests.setUserName(extensionRequestsDTO.getUserName());
        bizExtensionRequests.setCreateBy(extensionRequestsDTO.getUserName());

        // 插入延期申请
        bizExtensionRequestsMapper.insertBizExtensionRequests(bizExtensionRequests);

        return true;
    }


    /**
     * 申请验证
     */
    private void applyValidate(TQualityFileItem tQualityFileItem, List<BizExtensionRequests> bizExtensionRequests1) {
        if ("1".equals(tQualityFileItem.getOverdue())) {
            throw new RuntimeException("该项目已经超期，不能延期");
        }
        if (bizExtensionRequests1.stream().anyMatch(s -> "0".equals(s.getStatus()))) {
            throw new RuntimeException("正在审批中,请勿重复申请");
        }
    }
}
